﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Intelligent_Dapeng
{
    enum Conn_sta{
        Disconnect=0,   //断开连接
        connect,        //已连接
        Connecting,     //连接中
    };

    internal class ConnServer
    {
        private int SearchTimeout = 3000;  //连接超时时间
        string ip_str;
        int ip_port;
        Thread conn_th;
        Socket clientSocket;
        public Conn_sta conn_Sta = Conn_sta.Disconnect;

        /*阈值threshold   温度   湿度  光照*/
        public int temperature_thr, humidity_thr, illumination_thr;
        public int[] temperature = new int[600], humidity = new int[600], illumination = new int[600];
        public bool nowdata_sta = false;   //数据准备就绪标志
        public bool tempdata_sta = false;   //温度数据准备就绪标志
        public bool humidata_sta = false;   //湿度数据准备就绪标志
        public bool illudata_sta = false;   //光照数据准备就绪标志

        public ConnServer(string ip_str, int ip_port)
        {
            this.ip_str = ip_str;
            this.ip_port = ip_port;

            //Conn();
        }

        public void Conn()
        {
            conn_th = new Thread(do_ConnServer);
            conn_th.Start();
            conn_Sta = Conn_sta.Connecting;
        }



        private void do_ConnServer(object obj)
        {
            int Length;
            byte[] tmp_data = new byte[1024*16];

            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IAsyncResult connResult = clientSocket.BeginConnect(ip_str, ip_port, null, null);
            connResult.AsyncWaitHandle.WaitOne(SearchTimeout, true);

            if (!connResult.IsCompleted)
            {
                clientSocket.Close();
                clientSocket.Dispose();
                conn_Sta = Conn_sta.Disconnect;//连接失败
                return;
            }

            try
            {
                Length = clientSocket.Receive(tmp_data);
                clientSocket.Send(Encoding.UTF8.GetBytes("clientclientclient"));
            }
            catch (SocketException)
            {
                clientSocket.Close();
                clientSocket.Dispose();
                conn_Sta = Conn_sta.Disconnect;//连接失败
                return;
            }
            catch (ObjectDisposedException)
            {
                clientSocket.Close();
                clientSocket.Dispose();
                conn_Sta = Conn_sta.Disconnect;//连接失败
                return;
            }

            conn_Sta = Conn_sta.connect;//连接成功

            
            while (true)
            {
                try
                {
                    Length = clientSocket.Receive(tmp_data);
                }
                catch (SocketException)
                {
                    clientSocket.Close();
                    clientSocket.Dispose();
                    conn_Sta = Conn_sta.Disconnect;//断开连接
                    return;
                }
                catch (ObjectDisposedException)
                {
                    clientSocket.Close();
                    clientSocket.Dispose();
                    conn_Sta = Conn_sta.Disconnect;//断开连接
                    return;
                }

                /*server start 三个阈值 600*3个int,server end*/
                int start = 0, end = 0;
                for (int i = 0; i < Length; i++)
                {
                    if (tmp_data[i + 0] == 's' &&
                        tmp_data[i + 1] == 'e' &&
                        tmp_data[i + 2] == 'r' &&
                        tmp_data[i + 3] == 'v' &&
                        tmp_data[i + 4] == 'e' &&
                        tmp_data[i + 5] == 'r' &&
                        tmp_data[i + 6] == ' ' &&
                        tmp_data[i + 7] == 's' &&
                        tmp_data[i + 8] == 't' &&
                        tmp_data[i + 9] == 'a' &&
                        tmp_data[i +10] == 'r' &&
                        tmp_data[i +11] == 't' )
                    {
                        start = i + 12;
                    }

                    if (tmp_data[i + 0] == 's' &&
                        tmp_data[i + 1] == 'e' &&
                        tmp_data[i + 2] == 'r' &&
                        tmp_data[i + 3] == 'v' &&
                        tmp_data[i + 4] == 'e' &&
                        tmp_data[i + 5] == 'r' &&
                        tmp_data[i + 6] == ' ' &&
                        tmp_data[i + 7] == 'e' &&
                        tmp_data[i + 8] == 'n' &&
                        tmp_data[i + 9] == 'd' )
                    {
                        end = i;
                    }
                }

                

                if (start != 0 && end != 0)
                {
                    int type ;
                    /*获取温度湿度光照阈值数据*/
                    
                    type = 0;
                    for (start++; tmp_data[start] != ','; start++)
                    {
                        type *= 10;
                        type += tmp_data[start ] - '0';
                    }
                    /*开始数据*/
                    switch (type)
                    { 
                        case 0:
                            /*获取温度湿度光照阈值数据*/
                            
                            temperature_thr = 0;
                            for (start++; tmp_data[start] != ','; start++)
                            {
                                temperature_thr *= 10;
                                temperature_thr += tmp_data[start] - '0';
                            }

                            humidity_thr = 0;
                            for (start++; tmp_data[start] != ','; start++)
                            {
                                humidity_thr *= 10;
                                humidity_thr += tmp_data[start] - '0';
                            }

                            
                            illumination_thr = 0;
                            for (start++; tmp_data[start] != ','; start++)
                            {
                                illumination_thr *= 10;
                                illumination_thr += tmp_data[start ] - '0';
                            }
                            nowdata_sta = true;  //设置数据准备就绪
                            break;
                        case 1:
                            for (int f = 0; f < 600; f++)  //获取温度数据
                            {
                                temperature[f] = 0;
                                for (start++; tmp_data[start] != ','; start++)
                                {
                                    temperature[f] *= 10;
                                    temperature[f] += tmp_data[start] - '0';
                                }
                            }
                            tempdata_sta = true;
                            break;
                        case 2:
                            for (int f = 0; f < 600; f++)  //  获取湿度数据
                            {
                                humidity[f] = 0;
                                for (start++; tmp_data[start] != ','; start++)
                                {
                                    humidity[f] *= 10;
                                    humidity[f] += tmp_data[start] - '0';
                                }
                            }
                            humidata_sta = true;
                            break;
                        case 3:
                            for (int f = 0; f < 600; f++)  //获取光照数据
                            {
                                illumination[f] = 0;
                                for (start++; tmp_data[start] != ','; start++)
                                {
                                    illumination[f] *= 10;
                                    illumination[f] += tmp_data[start] - '0';
                                }
                            }
                            illudata_sta = true;
                            break;
                        default:
                            break;
                    }

                }
            }
        }

        public void Send_dat(int temperature_thr, int humidity_thr, int illumination_thr,
                             int heating_mode, int humidification_mode, int Filllight_mode)
        {
            string send_data = " client start ";
            if (temperature_thr < 10)       send_data += "0"+temperature_thr + ",";            else  send_data += temperature_thr + ",";            
            if (humidity_thr < 10)          send_data += "0" + humidity_thr + ",";             else  send_data += humidity_thr + ",";             
            if (illumination_thr < 10)      send_data += "0" + illumination_thr + ",";         else  send_data += illumination_thr + ",";         
            if (heating_mode < 10)          send_data += "0" + heating_mode + ",";             else  send_data += heating_mode + ",";             
            if (humidification_mode < 10)   send_data += "0" + humidification_mode + ",";      else  send_data += humidification_mode + ",";      
            if (Filllight_mode < 10)        send_data += "0" + Filllight_mode + " client end"; else  send_data += Filllight_mode + " client end";

            try
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(send_data));
            }
            catch (SocketException)
            {
                clientSocket.Close();
                clientSocket.Dispose();
                conn_Sta = Conn_sta.Disconnect;//断开连接
                return;
            }
            catch (ObjectDisposedException)
            {
                clientSocket.Close();
                clientSocket.Dispose();
                conn_Sta = Conn_sta.Disconnect;//断开连接
                return;
            }
        }
    }
}